#include "optionsdialog.h"
#include "ui_optionsdialog.h"

optionsDialog::optionsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::optionsDialog)
{
    ui->setupUi(this);
}

optionsDialog::~optionsDialog()
{
    delete ui;
}

void optionsDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void optionsDialog::run_form()
{
    setParameters();
    exec();
}

void optionsDialog::setParameters()
{
    QSettings settings("Affinity-Tools", "USBDriveFresher");
    ui->startupCheck->setChecked( settings.value("RunWithWindows", false ).toBool() );
    ui->runHiddenCheck->setChecked( settings.value("RunHidden", false ).toBool() );
    ui->autoCleanupCheck->setChecked( settings.value("AutoCleanup", false ).toBool() );
    ui->silentCheck->setChecked( settings.value("SilentAutoCleanup", false ).toBool() );

    settings.beginGroup("Rules");
    QStringList rulesList = settings.value("rulesStr", QString() ).toString().split( ';', QString::SkipEmptyParts );
    if ( rulesList.size() > 0 )
    {
        ui->listWidget->clear();
        for ( int i = 0; i < rulesList.size(); i++ )
            new QListWidgetItem( rulesList.at(i), ui->listWidget );
    }
    settings.endGroup();
}

void optionsDialog::on_saveButton_clicked()
{
    QSettings settings("Affinity-Tools", "USBDriveFresher");
    settings.setValue("RunWithWindows", ui->startupCheck->isChecked() );
    settings.setValue("RunHidden", ui->runHiddenCheck->isChecked() );
    settings.setValue("AutoCleanup", ui->autoCleanupCheck->isChecked() );
    settings.setValue("SilentAutoCleanup", ui->silentCheck->isChecked() );

    settings.beginGroup("Rules");
        settings.setValue("rulesStr", getRules() );
    settings.endGroup();

    accept();
}

QString optionsDialog::getRules() const
{
    QString rules;
    for ( int i = 0; i < ui->listWidget->count(); i++ )
    {
        rules.append( ui->listWidget->item(i)->text() );
        rules.append( ";" );
    }
    return rules;
}

void optionsDialog::on_autoCleanupCheck_stateChanged(int state)
{
    if ( state == 0 )
        ui->silentCheck->setChecked( false );
}

void optionsDialog::on_addButton_clicked()
{
    addRuleDialog addDlg(this);
    if ( addDlg.exec() )
    {
        ui->listWidget->addItem(
                new QListWidgetItem( addDlg.getRule(), ui->listWidget, 0) );
    }
}

void optionsDialog::on_modifyButton_clicked()
{
    if ( ui->listWidget->currentItem() )
    {
        addRuleDialog addDlg(this);
        addDlg.setRule( ui->listWidget->currentItem()->text() );
        if ( addDlg.exec() )
            ui->listWidget->currentItem()->setText( addDlg.getRule() );
    }
}

void optionsDialog::on_removeButton_clicked()
{
    if ( ui->listWidget->currentItem() )
    {
        ui->listWidget->takeItem(
                ui->listWidget->row( ui->listWidget->currentItem() ) );
    }
}
